<?php

/**
 * 快递一百查询接口
 * @author chenshubo
 */
namespace App\Service\VendorClient\OrderLogisticSearchApi;
use App\Service\BaseService;
use App\Service\HttpServer\Http;
class OrderLogisticSearchApiClient extends BaseService
{
    private $config = [];
    public function __construct( array $apiBody)
    {
        $this->config = $apiBody;
    }
    
    /**
     * 查询物流单号
     * @param string $express_sn
     */
    public function QueryLogisticByExpressSn( $express_sn = NULL )  
    {
        $param = [
            'express_sn' => $express_sn,
        ];
        $url = $this->config['queryExpressSnApi'];
        $com = $this->autoCom($param['express_sn']);
        if( !empty($com) && is_array($com) ){
            $post_data["customer"] = $this->config['customer'];
            $key= $this->config['key'];
            $param['mobile'] = isset($param['mobile'])?$param['mobile']:"";
            $param['express_sn'] = preg_replace("/[\s\v".chr(194).chr(160)."]+$/","", $param['express_sn']);
            $param['express_sn'] = preg_replace("/^[\s\v".chr(194).chr(160)."]+/","", $param['express_sn']);
            foreach ($com as $ka => $va ) {
                if( empty($va['comCode']) ) {
                    return [];
                }
                $comCode = $va['comCode'];
                $param_data = [
                    'com'   =>  $comCode,
                    'num'   =>  $param['express_sn'],
                    'phone' =>  $param['mobile'],
                    'from'  =>  '',
                    'to'    => '',
                    'resultv2' => ''
                ];
                $post_data['param'] = json_encode($param_data,true);
                $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
                $post_data["sign"] = strtoupper($post_data["sign"]);
                $temp = [];
                foreach ($post_data as $k => $v ) {
                    $v = urlencode($v);
                    $temp[] = "{$k}={$v}";
                }
        
                $fields = implode("&", $temp);
                $res = Http::post($url, $fields);
                $data = json_decode($res, true);
                if($data['message']=='ok'){
                    $info = $data['data'];
                    return $info;
                    break;
                }else{
                    $msg = $data['message'];
                }
            }
        
            return [];
        } else {
            return [];
        }
    }
    
    /**
     * 智能识别快递公司
     * @param string $express_sn
     */
    public function autoCom( $express_sn = '' )
    {
        $key = $this->config['key'];
        $url = $this->config['autoNumberApi'].'?num='.$express_sn.'&key='.$key;
        $res = Http::get($url);
        return @json_decode($res, true);
    }
}